/*
 * @lc app=leetcode.cn id=429 lang=golang
 *
 * [429] N 叉树的层序遍历
 */

// 2. 循环
// @lc code=start
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func levelOrder(root *Node) (ans [][]int) {
	nodes := []*Node{root}
	for len(nodes) > 0 {
		var temp []int
		var nextLevel []*Node
		for i := 0; i < len(nodes); i++ {
			if nodes[i] != nil {
				temp = append(temp, nodes[i].Val)
				nextLevel = append(nextLevel, nodes[i].Children...)
			}
		}
		if temp != nil {
			ans = append(ans, temp)
		}
		nodes = nextLevel
	}
	return
}

// @lc code=end

// 1. 递归
// @lc code=start
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func levelOrder(root *Node) (ans [][]int) {
	var level func(nodes []*Node)
	level = func(nodes []*Node) {
		if len(nodes) == 0 {
			return
		}
		temp := []int{}
		nextLevel := []*Node{}
		for _, node := range nodes {
			if node != nil {
				temp = append(temp, node.Val)
				nextLevel = append(nextLevel, node.Children...)
			}
		}
		if len(temp) > 0 {
			ans = append(ans, temp)
		}
		level(nextLevel)
	}

	level([]*Node{root})
	return
}

// @lc code=end

